# 此接口为管理员用户模块
from flask import Blueprint, jsonify, request
from models import User, Login, Task
from exts import db
import time

bp = Blueprint('admin', __name__, url_prefix="/admin")

# 管理员登录接口
@bp.route("/login", methods=["POST", "GET"])
def login():
    params = request.get_json() # {'admin_username': '763431', 'admin_password': '123'}
    # 验证登录
    admin_item = Login.query.filter_by(username=params["admin_username"], password=params["admin_password"]).first()
    if not admin_item:
        return jsonify({
            "status": 400,
            "msg": "no admin"
        })
    return jsonify({
        "status": 200,
        "msg": "login success"
    })

# 管理员获取数据
@bp.route("/get_data", methods=["POST", "GET"])
def get_data():
    params = request.get_json() # {'isLogin': True, 'form_num': 0}
    if not params["isLogin"]:
        return jsonify({
            "status": "400",
            "msg": "login fail"
        })
    
    task_ls = Task.query.filter_by(audit = params["form_num"]).all()
    """
                key: 1,
                tasktitle: 'go分布式web系统',
                bounty: 99,
                startdate: '2022-04-21',
                enddate: '2022-05-01',
                audit: '0',
                type_name: '软件开发',
                nickname: '默哀不易',
                email: '14342332@qq.com',
                taskintro: '利用go开发语言, k8s开发思路进行分布式的web系统开发'
    """
    data_ls = []
    for task in task_ls:
        startdate = time.strftime("%Y-%m-%d", time.localtime(int(task.createtime)))
        data = {
            "key": task.id,
            "tasktitle": task.tasktitle,
            "bounty": task.bounty,
            "startdate": startdate,
            "enddate": task.enddate,
            "audit": str(task.audit),
            "type_name": task.tasktype.typename,
            "nickname": task.user.nickname,
            "email": task.user.email,
            "taskintro": task.taskintro
        }

        data_ls.append(data)
    return jsonify({
        "status": 200,
        "data": data_ls
    })

# 管理员修改任务状态
@bp.route("/change_audit", methods=["POST", "GET"])
def change_audit():
    params = request.get_json() # {'id': 28, 'audit': '2'}
    task_item = Task.query.filter_by(id = params["id"]).first()
    if not task_item:
        return jsonify({
            "status": "400",
            "msg": "no have task"
        })
    task_item.audit = params["audit"]
    db.session.commit()
    return "success"
